package org.feng.interceptor;

import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.statement.select.PlainSelect;

/**
 * 数据权限拦截器
 *
 * @author fengjinsong
 */
@Slf4j
public class MybatisPlusPermissionInterceptor extends DataPermissionInterceptor {

    public MybatisPlusPermissionInterceptor(MyDataPermissionHandler dataPermissionHandler) {
        super(dataPermissionHandler);
    }

    /**
     * 设置 where 条件
     *
     * @param plainSelect  查询对象
     * @param whereStatement 查询条件片段
     */
    protected void setWhere(PlainSelect plainSelect, String whereStatement) {
        if (this.getDataPermissionHandler() instanceof MultiDataPermissionHandler) {
            super.processPlainSelect(plainSelect, whereStatement);
            return;
        }

        if(this.getDataPermissionHandler() instanceof MyDataPermissionHandler) {
            MyDataPermissionHandler handler = (MyDataPermissionHandler)this.getDataPermissionHandler();
            Expression sqlSegment = handler.getSqlSegmentWithPermission(plainSelect, whereStatement);
            if (null != sqlSegment) {
                plainSelect.setWhere(sqlSegment);
                log.info("追加权限控制：{}", plainSelect);
            }
        }
    }
}
